﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.Web;

namespace OCR
{
    public class GetBaiduApi
    {
        public string OCRclientId = ConfigurationManager.AppSettings["OCRClientId"];
        public string OCRclientSecret = ConfigurationManager.AppSettings["OCRClientSecret"];
        public string TranslateClientId = ConfigurationManager.AppSettings["TranslateClientId"];
        public string TranslateClientSecret = ConfigurationManager.AppSettings["TranslateClientSecret"];
        static string Token = string.Empty;
        public string GetAccessToken(string client_id, string secret)
        {
            try
            {
                if (OCRclientId != "" && OCRclientSecret != "")
                {
                    String authHost = "https://aip.baidubce.com/oauth/2.0/token";
                    HttpClient client = new HttpClient();
                    List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
                    paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    paraList.Add(new KeyValuePair<string, string>("client_id", client_id));
                    paraList.Add(new KeyValuePair<string, string>("client_secret", secret));
                    HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
                    String result = response.Content.ReadAsStringAsync().Result;
                    var objToken = JsonConvert.DeserializeObject<JObject>(result);
                    if (objToken != null)
                    {
                        Token = objToken["access_token"].ToString();
                    }
                    return Token;
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                MessageBox.Show("AccessToken错误");
            }
            return "";
        }
        public string textTrans(string Len, string Text)
        {
            if (GetAccessToken(TranslateClientId, TranslateClientSecret) != "") {
                string host = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + GetAccessToken(TranslateClientId, TranslateClientSecret);
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                String str = "{\"from\":\"auto\",\"to\":\"" + Len + "\",\"q\":\"" + Text + "\"}";
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd();
                return result;
            }
            else
            {
                return "";
            }
            //if (TranslateClientId==""&& TranslateClientSecret=="")
            //{
            //    MessageBox.Show("请点击设置添加'TranslateClientId'和'TranslateClientSecret'");
            //    return "null";
            //}
            //else
            //{
                
            //}
        }

        // OCR 通用识别（带坐标）
        public string general(string ImgPath)
        {
            if (GetAccessToken(TranslateClientId, TranslateClientSecret) != "")
            {
                string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + GetAccessToken(OCRclientId, OCRclientSecret);
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                // 图片的base64编码
                string base64 = getFileBase64(ImgPath);
                String str = "image=" + HttpUtility.UrlEncode(base64);
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd();
                return result;
            }
            else
            {
                return "";
            }
        }
        public String getFileBase64(String fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
        public string Gen(System.Drawing.Image ImgPath)
        {

            if (OCRclientId==""&& OCRclientSecret=="")
            {
                MessageBox.Show("请点击设置添加'OCRclientId'和'OCRclientSecret'");
                return "null";
            }
            else
            {
                string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=" + GetAccessToken(OCRclientId, OCRclientSecret);
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                // 图片的base64编码
                string base64 = ImageToBase64(ImgPath);
                String str = "image=" + HttpUtility.UrlEncode(base64);
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd();
                return result;
            }
        }
        public string ImageToBase64(System.Drawing.Image bmp)
        {
            if (bmp != null)
            {
                try
                {
                    MemoryStream ms = new MemoryStream();
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    byte[] arr = new byte[ms.Length]; ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length); ms.Close();
                    return Convert.ToBase64String(arr);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + $"出错代码行：{ex.StackTrace}");
                    return "";
                }
            }
            return "";
        }
    }
}
